package com.example.star.mapper;

import com.example.star.entity.User;
import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
@Mapper
public interface UserMapper {


    @Select("SELECT * FROM users WHERE role = 'user'")
    List<User> getNormalUsers();

    @Select("SELECT * FROM users WHERE role = 'admin'")
    List<User> getAdminUsers();
    // 注册用户
    @Insert("INSERT INTO users (username,nickname, password,avatar,money,role) VALUES (#{username},  #{nickname},#{password}, #{avatar},#{money}, #{role})")
    void insertUser(User user);

    // 根据用户名查询用户
    @Select("SELECT * FROM users WHERE username = #{username}")
    Optional<User> findByUsername(String username);

    // 根据昵称查询用户
    @Select("SELECT * FROM users WHERE nickname = #{nickname}")
    Optional<User> findByNickname(String nickname);

    @Select("SELECT * FROM users")
    List<User> getAllUsers();

    @Delete("DELETE FROM users WHERE id = #{id}")
    void deleteUserById(Integer id);

    @Select("SELECT * FROM users WHERE id = #{id}")
    Optional<User> findUserById(Integer id);
    @Update("UPDATE users SET username = #{username}, password = #{password}, nickname = #{nickname}, avatar = #{avatar}, role = #{role} WHERE id = #{id}")
    void updateUser(User user);

    @Select("SELECT * FROM users WHERE username = #{username}")
    User getUserByUsername(String username);

    @Update("UPDATE users SET password = #{password}, nickname = #{nickname} WHERE username = #{username}")
    void updateUserByUsername(
            @Param("username") String username,
            @Param("password") String password,
            @Param("nickname") String nickname);


    @Update("UPDATE users SET avatar = #{avatar} WHERE username = #{username}")
    void changeUserAvatar(@Param("username") String username,
                       @Param("avatar") String avatar);

    @Update("UPDATE users SET password = #{newPassword} WHERE username = #{username}")
    void changeUserPassword(@Param("username") String username,
                        @Param("newPassword") String newPassword);

    @Update("UPDATE users SET money = COALESCE(money, 0)  + #{amount} WHERE username = #{username}")
    int updateMoney(String username, double amount);

    @Update("UPDATE users SET money = #{money} WHERE username = #{username}")
    int updateUserMoney(String username, BigDecimal money);

    // 检测用户余额
    @Select("SELECT money FROM users WHERE username = #{username}")
    BigDecimal checkMoney(@Param("username") String username);
}
